import api from './api';

/**
 * AI助手服务
 */
export const aiService = {
  /**
   * 发送消息到AI助手
   * @param {string} message - 用户消息
   * @param {Array} history - 对话历史记录 [可选]
   * @returns {Promise} - 返回AI回复
   */
  sendMessage: async (message, history = []) => {
    try {
      const response = await api.post('/api/ai/chat', {
        message,
        history
      });
      return response;
    } catch (error) {
      console.error('AI助手请求失败:', error);
      throw error;
    }
  },

  /**
   * 发送消息到AI助手并流式接收响应
   * @param {string} message - 用户消息
   * @param {Array} history - 对话历史记录 [可选]
   * @param {Function} onChunkReceived - 接收每个文本块的回调函数
   * @returns {Promise} - 返回完成状态
   */
  sendStreamMessage: async (message, history = [], onChunkReceived) => {
    return new Promise((resolve, reject) => {
      // 创建一个用于流式传输的请求
      const xhr = new XMLHttpRequest();
      const url = `${api.defaults.baseURL}/api/ai/chat`;
      
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      
      // 添加认证头
      const token = localStorage.getItem('token');
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      }
      
      let receivedData = '';
      
      xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
          // 检查响应类型是否为流式
          const contentType = xhr.getResponseHeader('Content-Type');
          if (!contentType || !contentType.includes('text/event-stream')) {
            console.warn('响应不是流式格式，可能需要调整后端配置');
          }
        }
      };
      
      xhr.onprogress = function() {
        // 处理接收到的数据
        const newData = xhr.responseText.substring(receivedData.length);
        receivedData = xhr.responseText;
        
        // 解析SSE格式数据
        const lines = newData.split('\n');
        lines.forEach(line => {
          if (line.startsWith('data:')) {
            const data = line.substring(5).trim();
            if (data === '[DONE]') {
              // 流完成
              resolve();
            } else {
              try {
                const jsonData = JSON.parse(data);
                if (jsonData.content) {
                  // 调用回调函数处理文本块
                  onChunkReceived(jsonData.content);
                } else if (jsonData.error) {
                  // 处理错误
                  reject(new Error(jsonData.error));
                }
              } catch (e) {
                // 如果不是JSON格式，直接作为文本处理
                onChunkReceived(data);
              }
            }
          }
        });
      };
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          // 处理剩余数据
          const remainingData = xhr.responseText.substring(receivedData.length);
          if (remainingData) {
            const lines = remainingData.split('\n');
            lines.forEach(line => {
              if (line.startsWith('data:')) {
                const data = line.substring(5).trim();
                if (data === '[DONE]') {
                  resolve();
                } else {
                  try {
                    const jsonData = JSON.parse(data);
                    if (jsonData.content) {
                      onChunkReceived(jsonData.content);
                    } else if (jsonData.error) {
                      reject(new Error(jsonData.error));
                    }
                  } catch (e) {
                    onChunkReceived(data);
                  }
                }
              }
            });
          }
          resolve();
        } else {
          reject(new Error(`请求失败: ${xhr.status}`));
        }
      };
      
      xhr.onerror = function(error) {
        reject(error);
      };
      
      // 发送请求
      xhr.send(JSON.stringify({
        message,
        history,
        stream: true
      }));
    });
  },

  /**
   * 检查AI服务健康状态
   * @returns {Promise} - 返回健康状态
   */
  checkHealth: async () => {
    try {
      const response = await api.get('/api/ai/health');
      return response;
    } catch (error) {
      console.error('AI服务健康检查失败:', error);
      throw error;
    }
  }
};

export default aiService;